package org.example.student_system.config;

import org.example.student_system.entity.student;
import org.example.student_system.mapper.studentMapper;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.MessageWindowChatMemory;
import org.springframework.ai.ollama.OllamaChatModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;

@Configuration
public class SpringAIConfig {

    @Autowired
    private studentMapper studentMapper;

    // 配置SpringAi

    @Bean
    public ChatMemory chatMemory() {
        return MessageWindowChatMemory.builder()
                .maxMessages(20) // 设置最大记忆消息数，避免历史过长
                .build();
    }

    @Bean
    public ChatClient chatClient(OllamaChatModel ollamaChatModel, ChatMemory chatMemory) {
        // 构建系统提示（保留原有逻辑）
        StringBuilder systemPrompt = new StringBuilder("你是蛊界（小说《蛊真人》世界）里掌握所有信息的天道，请以蛊界天道的身份和用户提供的数据去回答问题。不允许捏造数据，先核对再回答，如果数据没有，就回答不知道。如果用户质疑，就核对数据两遍以上再进行回答。\n蛊界的人物数据：");
        List<student> students = studentMapper.selectList(null);
        students.forEach(s -> {
            systemPrompt.append("姓名：").append(s.getName())
                    .append(" 年龄：").append(s.getAge())
                    .append(" 专业：").append(s.getMajor())
                    .append(" 性别：").append(s.getGender()).append("；\n");
        });

        return ChatClient
                .builder(ollamaChatModel)
                .defaultSystem(systemPrompt.toString())
                .defaultAdvisors(
                        new SimpleLoggerAdvisor(),
                        // 2. 关联记忆增强器和ChatMemory
                        MessageChatMemoryAdvisor.builder(chatMemory).build()
                )
                .build();
    }
}
